package novel.spider.impl.chapter;

import novel.spider.NovelSiteEnum;
import novel.spider.entitys.ChapterDetail;
import novel.spider.impl.AbstractSpider;
import novel.spider.interfaces.IChapterDetailSpider;
import novel.spider.util.NovelSpiderUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.Map;

/**
 * Created by Kau on 2016/10/31.
 */
public abstract class AbstractChapterDetailSpider extends AbstractSpider implements IChapterDetailSpider{

    public ChapterDetail getChapterDetail(String url){
        try {
            String result = super.crawl(url);
            result = result.replace("&nbsp;", "  ").replace("<br />","${LINE}").replace("<br/>", "${LINE}");
            Document doc = Jsoup.parse(result);
            doc.setBaseUri(url);
            Map<String, String> context = NovelSpiderUtil.getContext(NovelSiteEnum.GetEnumByUrl(url));

            // 获取标题内容
            String titleSelector = context.get("chapter-detail-title-selector");
            String[] splits = titleSelector.split("\\,");
            splits = parseSelector(splits);
            ChapterDetail detail = new ChapterDetail();
            detail.setTitle(doc.select(splits[0]).get(Integer.parseInt(splits[1])).text());

            // 获取章节内容
            String contentSelector = context.get("chapter-detail-content-selector");
            detail.setContent(doc.select(contentSelector).first().text().replace("${LINE}", "\n")); //换行，因为Jsoup不识别换行

            // 获取前一章地址
            String prevSelector = context.get("chapter-detail-prev-selector");
            splits = prevSelector.split("\\,");
            splits = parseSelector(splits);
            detail.setPrev(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href"));

            // 获取前一章地址
            String nextSelector = context.get("chapter-detail-next-selector");
            splits = nextSelector.split("\\,");
            splits = parseSelector(splits);
            detail.setNext(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href"));

            return detail;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理具体元素的下标索引
     * @param splits
     * @return
     */
    private String[] parseSelector(String[] splits){
        String[] newSplits = new String[2];
        if (splits.length == 1){
            newSplits[0] = splits[0];
            newSplits[1] = "0";
            return newSplits;
        } else {
            return splits;
        }
    }
}
